var statusBar = null;
var configurationMonitor = null;

var KEY_CONFIGURATION_SOURCE = 'cc_monitor_configuration_source';
var KEY_INTERVAL = 'cc_monitor_interval';

function init() {
  initConfiguration();
  initButton();
  statusBar = $('status-bar');
  configurationMonitor = new ConfigurationMonitor('configuration_source', 'interval', showPrefs); 
  
  setTimeout('restartMonitors()', 10);
  
  // for fixing gif does not active when showing widget after hide dashboard a long time
  if(window.widget) {
    window.widget.onshow = function() {
      configurationMonitor.spinner.redraw();
      new Version().update();
    }
  }
}

function initConfiguration() {
  if(window.widget) {
    var source = window.widget.preferenceForKey(KEY_CONFIGURATION_SOURCE)
    if(source) {
      $('configuration_source').value = source;
    }
    
    var interval = window.widget.preferenceForKey(KEY_INTERVAL);
    if(interval) {
      $('interval').value = interval
    }
  }
}

function saveConfiguration() {
  if(window.widget) {
    window.widget.setPreferenceForKey($('configuration_source').value, KEY_CONFIGURATION_SOURCE);
    window.widget.setPreferenceForKey($('interval').value, KEY_INTERVAL);
  }
}

function reboot() {
  configurationMonitor.reboot();
  $('start-button').hide();
  $('stop-button').show();
}

function restartMonitors() {
  $('start-button').hide();
  $('stop-button').show();
  configurationMonitor.restart();
}

function stopMonitors() {
  $('stop-button').hide();
  $('start-button').show();
  configurationMonitor.stop();
}

function log(msg) {
}

function alert(msg) {
  statusBar.innerHTML = msg;
  statusBar.title = msg;
}

function openLink(link) {
  if(window.widget) {
    window.widget.openURL(link.href)
  }else {
    alert(link.href)
  }
}

function initButton() {
  if (window.widget) {
    new AppleGlassButton($("doneButton"), "Done", hidePrefs);
    var gInfoButton = new AppleInfoButton($("infoButton"), $("front"), "white", "white", showPrefs);
    gInfoButton.setStyle("black", "black");
  }else {
    $('infoButton').innerHTML = '<input type="button" value="i" onclick="showPrefs()"/>'
    $('doneButton').innerHTML = '<input type="button" value="Done" onclick="hidePrefs()"/>'
  }
}

function hidePrefs() {
  if (window.widget)
    widget.prepareForTransition("ToFront");

  $('front').show();
  $('back').hide();

  if (window.widget)
    setTimeout('widget.performTransition();', 0);

  saveConfiguration();
  configurationMonitor.endSetup();
}

function showPrefs() {
  if (window.widget)
    widget.prepareForTransition("ToBack");
  $('front').hide();
  $('back').show();
  if (window.widget)
    setTimeout('widget.performTransition();', 0);

  configurationMonitor.startSetup();
}
